package register

import (
	"github.com/go-redis/redis"
	"github.com/mohong122/ip2region/binding/golang"
	"log"
	"sync"
	"time"
)

type Server struct {
	localHost  string
	remoteHost string
	scheduler  string
	lock sync.Mutex
	clients map[string]Client
	register chan *Client
	IpRegion      *ip2region.Ip2Region
	RegionDecoder RegionDecoder
	RDB		*redis.Client
}

func (s *Server) SetLocalHost(local string) {
	s.localHost = local
}
func (s *Server) SetRemoteHost(remote string) {
	s.remoteHost = remote
}
func (s *Server) SetScheduler(scheduler string) {
	s.scheduler = scheduler
}

func NewServer() *Server {
	return &Server{
		register: make(chan *Client),
		clients: make(map[string]Client),
	}
}

func (s *Server) UploadToBili(day, minute string)  {
	log.Printf("[UploadToBili] day: %s minute: %s time: %v", day, minute, time.Now())
	originTrafficDay, err := s.RDB.ZScore("origin_traffic", day).Result() //MB
	if err != nil {
		log.Printf("[UploadToBili] get origin_traffic day err:%s", err.Error())
	}
	originTrafficMinute, err := s.RDB.ZScore("origin_traffic", minute).Result() //MB
	if err != nil {
		log.Printf("[UploadToBili] get origin_traffic minute err:%s", err.Error())
	}
	cacheTrafficDay, err := s.RDB.ZScore("cache_traffic", day).Result() //MB
	if err != nil {
		log.Printf("[UploadToBili] get cache_traffic day err:%s", err.Error())
	}
	cacheTrafficMinute, err := s.RDB.ZScore("cache_traffic", minute).Result() //MB
	if err != nil {
		log.Printf("[UploadToBili] get cache_traffic minute err:%s", err.Error())
	}

	originTraffic := originTrafficDay / float64(1024) //GB
	originBandwidth := originTrafficMinute * float64(8) / float64(1024) / float64(300) //Gbps
	cacheTraffic := cacheTrafficDay / float64(1024) //GB
	cacheBandwidth := cacheTrafficMinute * float64(8) / float64(1024) / float64(300) //Gbps

	log.Printf("[UploadToBili] originTraffic:%v, originBandwidth:%v, cacheTraffic:%v, cacheBandwidth:%v", originTraffic, originBandwidth, cacheTraffic, cacheBandwidth)

	/*post := `origin_bandwidth{format="dash"} 2.2
origin_bandwidth{format="flv"} 2.2
scdn_bandwidth{format="dash"} 2.2
scdn_bandwidth{format="flv"} 2.2
`
	fmt.Println(post)
	var jsonstr = []byte(post) //转换二进制
	buffer:= bytes.NewBuffer(jsonstr)
	request, err := http.NewRequest("POST", "http://bvc.bilivideo.com/pushgateway/metrics/job/publicpush/instance/pear_2c979f20", buffer)
	if err != nil {
		fmt.Printf("[UploadToBili] http.NewRequest err: %s", err.Error())
		return
	}
	//request.Header.Set("Content-Type", "application/json;charset=UTF-8")  //添加请求头
	resp, err := http.DefaultClient.Do(request) //发送请求
	if err != nil {
		fmt.Printf("client.Do err: %s", err.Error())
		return
	}
	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("ioutil.ReadAll err: %s", err.Error())
		return
	}
	log.Printf("[UploadToBili] resp StatusCode:%v body:%v", resp.StatusCode, string(respBytes))*/

}
func (s *Server) Run() {
	go func(server *Server) {
		for {
			log.Printf("[info]:server run starting")
			server.lock.Lock()
			nodeCount := len(server.clients)
			if nodeCount!= 0 {
				for m, c := range server.clients {
					if time.Now().Unix()-c.nodeAnnounce.Time > c.nodeAnnounce.Timeout * 2 + 60 {
						log.Printf("time last:%d,timeout:%d",time.Now().Unix()-c.nodeAnnounce.Time,c.nodeAnnounce.Timeout)
						delete(server.clients, m)
					}
				}
			}
			server.lock.Unlock()
			log.Printf("[info]:server current total node amount:%d",nodeCount)
			log.Printf("[info]:server run entering sleeping")
			time.Sleep(time.Second * 330)
		}
	}(s)

	go func(server *Server) {
		for {
			now := time.Now()
			next := time.Now().Add(time.Minute * 5)
			next = time.Date(next.Year(), next.Month(), next.Day(), next.Hour(), (next.Minute()/5) * 5, 0, 0, next.Location())
			dayStr := now.Format("2006_01_02")
			minuteStr := next.Format("2006_01_02_15_04")
			t := time.NewTimer(next.Sub(now))
			<-t.C
			s.UploadToBili(dayStr, minuteStr)
		}
	}(s)
}

